package com.xxjz.sc.controller.pic;
import com.xxjz.sc.servers.util.IMinioClientServers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@RestController
public class MiniFileController {



    @Autowired
    IMinioClientServers minioClientServers;

    @Value("${minio.url}")
    String minioUrl;

    @Value("${minio.bucket-name}")
    String minioBucket;

    /**
     * 上传普通图片
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadPic")
    public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("model") String model) throws Exception {
        JSONObject object = new JSONObject();

        if (file.isEmpty()) {
            throw new Exception("上传文件不能为空");
        } else {
            final String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString();
            String path = "";
            path = "commonpic/" + model + "/" + uuid + fileName.substring(fileName.lastIndexOf("."), fileName.length() );
            byte[] bytes = file.getBytes();
            minioClientServers.uploadFile(bytes, path, "");
            return minioUrl + "/" + minioBucket + "/" + path;
        }
    }

    @PostMapping("/uploadHeadPic")
    public String uploadHeadPic(@RequestParam("file") MultipartFile file) throws Exception {
        JSONObject object = new JSONObject();
        if (file.isEmpty()) {
            throw new Exception("上传文件不能为空");
        } else {
            final String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString();
            String path = "";
            path = "headpic/" + uuid + fileName.substring(fileName.lastIndexOf("."), fileName.length() - 1);
            byte[] bytes = file.getBytes();
            minioClientServers.uploadFile(bytes, path, "");
            return minioUrl + "/" + minioBucket + "/" + path;
        }
    }
}